package com.tdam2013.grupo07.networking;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.tdam2013.grupo07.mensajes.ChatMensaje;

public class QueryMessagesHandler extends DefaultHandler {

	private QueryMessagesResponse response;	
	private ChatMensaje tempMessage;
	private boolean inMessage;
	
	public QueryMessagesResponse getResponse()
	{
		return response;
	}

	public QueryMessagesHandler()
	{
		tempMessage=null;
		inMessage=false;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
	{
		super.startElement(uri, localName, qName, attributes);
		if (qName.equalsIgnoreCase("RESULT"))
		{
			response=new QueryMessagesResponse();
			response.setSuccess(attributes.getValue(attributes.getIndex("type")).equalsIgnoreCase("success")?true:false);
			response.setId(attributes.getValue(attributes.getIndex("type")));
		}
		else if(qName.equalsIgnoreCase("DETAIL"))
		{
			response.setErrorCode(Integer.parseInt(attributes.getValue(attributes.getIndex("code"))));
			response.setErrorDescription(attributes.getValue(attributes.getIndex("description")));
		}
		else if(qName.equalsIgnoreCase("MESSAGE"))
		{
			inMessage=true;
			tempMessage=new ChatMensaje();
			String timestamp=attributes.getValue(attributes.getIndex("timestamp"));
			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
			Date fecha=null;
			try
			{
				fecha= simpleDateFormat.parse(timestamp);
			}
			catch(ParseException ex)
			{
				
			}
			tempMessage.setFecha(fecha);
			tempMessage.setDestinatario(attributes.getValue(attributes.getIndex("from")));
		}
	}
	
	@Override
	public void endElement(String uri,String localName,String qName)
	{
		if(inMessage)
		{
			inMessage=false;
			tempMessage.setTipo(ChatMensaje.TIPO_ENTRANTE);
			response.addMessage(tempMessage);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException 
	{
		super.characters(ch, start, length);
		if(inMessage)
		{
			tempMessage.setTexto(new String(ch, start, length));
		}
	}
}
